import { QuestDefaultApi } from '@/library/util/api';
import { defaultErrorHandler } from '@/library/util/error-handler';
import { message } from 'ant-design-vue';
import { defineStore } from 'pinia';
import { QuestionResult } from '../answer/types';
import QuestAdapter from '../design/adpater/QuestAdapter';
import { Questionaire } from '../design/types';
import EditAdapter from './adapter/EditAdapter';
import EditBasic from './types/EditBasic';
interface SettingBasicState {
  queId: string;

  /** 问卷信息 */
  questionaire: Questionaire | undefined;

  isLoading: boolean;
}
export const useSettingBasicStore = defineStore({
  id: 'SettingBasicStore',
  state: (): SettingBasicState => ({
    queId: '',
    questionaire: new Questionaire(),
    isLoading: false,
  }),
  actions: {
    /**
     * 设置当前操作id 并请求问卷信息
     * @param value
     */
    setQuestId(value: string) {
      this.queId = value;
    },

    /** 编辑时请求问卷信息 */
    async queryDetails(queId: string) {
      try {
        if (!queId) {
          throw new Error('请刷新重试');
        }

        this.isLoading = true;
        const result =
          (await QuestDefaultApi.questionaireQuestionaireDetailsGet({
            queId: queId,
          })) as QuestionResult;

        if (result) {
          this.setQuestionaire(new QuestAdapter().compose(result));
        }
      } catch (error) {
        defaultErrorHandler(error);
      }
    },

    setQuestionaire(value: Questionaire) {
      this.questionaire = value;
    },

    async edit() {
      try {
        if (!this.questionaire) {
          throw new Error('请刷新重试');
        }
        await QuestDefaultApi.questionaireEditQuestionaireConfigPost(
          new EditAdapter().compose(this.questionaire),
        );

        message.success('问卷基本信息修改完成');
      } catch (error) {
        defaultErrorHandler(error);
      }
    },

    setStartTime(startTime: string) {
      if (!this.questionaire) return;
      this.questionaire.startTime = startTime;
    },

    setEndTime(value: string) {
      if (!this.questionaire) return;
      this.questionaire.endTime = value;
    },

    setInfor(value: EditBasic) {
      if (!this.questionaire) return;
      console.log(value);
      this.questionaire.startTime = value.startTime;
      this.questionaire.endTime = value.endTime;
      this.questionaire.submissionTips = value.tips;
      this.questionaire.queTitle = value.title;
      this.questionaire.submissionTips = value.submit;
    },
  },
});
